#! user/bin/env python
# -*- coding:utf-8 -*-

import requests
import http.cookiejar
import lxml
import re
import time
import os.path
import matplotlib.pyplot as plt
from PIL import Image
from bs4 import BeautifulSoup

# make request header
url = 'https://www.zhihu.com/'
loginUrl = 'https://www.zhihu.com/login/email'
captchaImgUrl = url + 'captcha.gif?r=' + str(
    int(time.time() * 1000)) + '&type=login'

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
    'Referer': 'https://www.zhihu.com/',
    'Host': "www.zhihu.com",
    'Accept-Encoding': 'gzip, deflate, br'
}

cookie = 'cookies.txt'
session = requests.Session()
session.cookies = http.cookiejar.MozillaCookieJar(cookie)
if os.path.exists(cookie):
    try:
        session.cookies.load(ignore_discard=True)
        print("load cookie succeed")
    except:
        print("cookie load failed")
else:
    print("cookie not existed")


def _getXsrf():
    """
    get xsrf and captcha for login, return a tumple.
    :return:(xsrf, captcha) 
    """
    response = session.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'lxml')
    xsrf = soup.input['value']
    return xsrf


def _getCaptcha():
    r = session.get(captchaImgUrl, headers=headers)
    with open('captcha.jpg', 'wb') as fl:
        fl.write(r.content)
    im = Image.open('captcha.jpg')
    im.show()
    captcha = input('please input captcha')
    return captcha


def login(username, passwd):
    """
    :param username: zhihu username 
    :param passwd: zhihu passwd
    :return: 
    """

    #  select login ways, email or phone

    if re.match(r'^\d+$', username):
        print("use phone to login... please use email to login")
    else:
        print("use email to login...")
        xsrf = _getXsrf()
        data = {
            '_xsrf': xsrf,
            'password': passwd,
            'email': username,
            'captcha_type': 'cn'
        }
        print("make data succeed")
    try:
        print('try to use cookie to login')
        r = session.post(loginUrl, data=data, headers=headers)
        print(r.status_code)
    except:
        print("cookie login failed. try to get captcha...")
        data['captcha'] = _getCaptcha()
        print("begin to login...")
        print(data)
        r = session.post(loginUrl, data=data, headers=headers)
        print(r.status_code)
    session.cookies.save()


# username = input('please input username:')
# passwd = input('please input password:')
username = 'fc896745130@163.com'
passwd = 'fc19930207'
login(username, passwd)
